package ctbu.edu.cn.dp101.service;


import ctbu.edu.cn.dp101.constant.REnum;
import ctbu.edu.cn.dp101.dao.StudentRepository;
import ctbu.edu.cn.dp101.entity.Student;
import ctbu.edu.cn.dp101.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.naming.Name;
import java.util.List;

@Service
public class StudentService {

    @Autowired
    public StudentRepository studentRepository;

    /*
    @return
     */


    public List<Student> getAll() {

        return studentRepository.findAll();

    }

    //分页
    public Page<Student> getAll(Pageable pageable) {

        return studentRepository.findAll(pageable);

    }

    public Page<Student> getAll(Example<Student> example, Pageable pageable) {

        return studentRepository.findAll(example, pageable);

    }

    public Student findById(int id) {

        return studentRepository.findById(id).get();

    }


    /**
     * 新增学生
     * @param student
     * @return
     */
    public Student add(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 更新学生
     * @param student
     * @return
     */
    public Student update(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 删除学生
     * @param id
     *
     */
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }

    public List<Student> findByNameLike(String name) {

        return studentRepository.findByNameLike("%"+name+"%");

    }

    public List<Student> findBySnoLike(String sno) {

        return studentRepository.findByTnoLike("%"+sno+"%");

    }

    public Student validateUsernameAndPassword(String sno, String password) throws Exception {

        List<Student> students = studentRepository.findByTno(sno);
        if (students.size() > 0) {
            //可能对password加密，但我们暂时不做处理
            Student student = students.get(0);
            if (student.getPassword().equals(password)){

                //成功
                return student;
            }else {
                throw new RException(REnum.LOGIN_ERR);
            }
        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }


}
